﻿/**
 * 线程执行取消类CancellationTokenSource使用示例
 * author: zjh
 * create: 2019-08-02 14:15
 * 
 * */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CancellationTokenSourceClass
{
    class Program
    {
        static CancellationTokenSource cancelSource;
        static void Main(string[] args)
        {
            Console.WriteLine("program start.");
            cancelSource = new CancellationTokenSource();
            Thread workerThread = new Thread(Worker);
            workerThread.IsBackground = true;
            workerThread.Start();

            var line = string.Empty;
            while (!(line = Console.ReadLine()).Equals("exit", StringComparison.OrdinalIgnoreCase))
            {
                if (line.Equals("cancel"))
                {
                    // 取消工作线程执行
                    cancelSource.Cancel();
                }
            }

            Console.WriteLine("program end.");
            Console.ReadLine();
        }

        private static void Worker()
        {
            var token = cancelSource.Token;
            Console.WriteLine("working thread start.");
            while (true)
            {
                try
                {
                    // method 1.
                    token.ThrowIfCancellationRequested();
                    // method 2.
                    //if (token.IsCancellationRequested)
                    //{
                    //    Console.WriteLine("working thread canceled.");
                    //    break;
                    //}
                    Console.WriteLine("do something...");
                    Thread.Sleep(500);
                }
                catch (OperationCanceledException ex)
                {
                    Console.WriteLine("working thread canceled.");
                    Console.WriteLine("exception: {0}", ex.Message);
                    break;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("exception: {0}", ex.Message);
                    break;
                }
            }
            Console.WriteLine("working thread end.");
        }
    }
}
